package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"time"
)

func test() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run()
}

func test2() {
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}

	r.Use(func(c *gin.Context) { //middleware会在所有请求前执行，调用没有的路径也会执行middleware
		// 记录path, response code, log latency
		logger.Info("incoming request", zap.String("path", c.Request.URL.Path))

		c.Next() // 请求真正的处理
	})

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.GET("/hello", func(c *gin.Context) {
		c.String(200, "hello")
	})
	r.Run()
}

func test3() {
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}

	r.Use(func(c *gin.Context) { //middleware会在所有请求前执行，调用没有的路径也会执行middleware
		s := time.Now()

		c.Next() // 请求真正的处理

		// 记录path, response code, log latency
		logger.Info("incoming request",
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()), // 状态码只能在请求处理后获取
			zap.Duration("elapsed", time.Now().Sub(s)))
	})

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.GET("/hello", func(c *gin.Context) {
		c.String(200, "hello")
	})
	r.Run()
}

const keyRequestId = "requestId"

func test4() {
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}

	r.Use(func(c *gin.Context) { //middleware会在所有请求前执行，调用没有的路径也会执行middleware
		s := time.Now()

		c.Next() // 请求真正的处理

		// 记录path, response code, log latency
		logger.Info("incoming request",
			zap.String("path", c.Request.URL.Path),
			zap.Int("status", c.Writer.Status()), // 状态码只能在请求处理后获取
			zap.Duration("elapsed", time.Now().Sub(s)))
	}, func(c *gin.Context) { // 给每个请求加id
		c.Set(keyRequestId, rand.Int())

		c.Next()
	})

	r.GET("/ping", func(c *gin.Context) {
		h := gin.H{
			"message": "pong",
		}
		if rid, exists := c.Get(keyRequestId); exists {
			h[keyRequestId] = rid
		}
		c.JSON(200, h)
	})
	r.GET("/hello", func(c *gin.Context) {
		c.String(200, "hello")
	})
	r.Run()
}

func main() {
	//test()
	//test2()
	//test3()
	test4()
}
